package com.cairenhui.trust.auto.task.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cairenhui.trust.auto.task.dao.BaseOrganizationMapper;
import com.cairenhui.trust.auto.task.dao.DepartmentVMapper;
import com.cairenhui.trust.auto.task.model.BaseOrganization;
import com.cairenhui.trust.auto.task.model.BaseOrganizationExample;
import com.cairenhui.trust.auto.task.model.DepartmentV;
import com.cairenhui.trust.auto.task.model.DepartmentVExample;
import com.cairenhui.trust.auto.task.model.Page;
import com.cairenhui.trust.auto.task.service.TaskService;
import com.cairenhui.trust.auto.task.util.DateUtils;
import com.cairenhui.trust.auto.task.util.constant.StatusConstants;


/**
 * 
 * @author 黄瑞庆
 * TODO 部门（更新）任务
 * 2017年2月27日
 */
@Component
public class BaseOrgTaskService extends TaskService{
	
	//self4j日志
	private Logger logger = LoggerFactory.getLogger(BaseOrgTaskService.class);
	
	@Autowired
	private DepartmentVMapper departmentVMapper;
	@Autowired
	private BaseOrganizationMapper baseOrganizationMapper;
	
	/**
	 * 
	 * TODO 同步部门信息方法
	 * @author 黄瑞庆
	 * void
	 * 2017年3月2日 下午6:54:41
	 */
	@Override
	public void sysCrm() {
		
		DepartmentVExample example = new DepartmentVExample();
		//获取视图中总条数
		TOTAL_COUNT = departmentVMapper.countByExample(example); 
		//根据每页查询数 ，总条数 计算出 总页数
		Page<DepartmentV> pageTemp = new Page<DepartmentV>(1, QUERY_NUM,TOTAL_COUNT);
		
		//开启分页查询
		for(int i = 1 ; i<= pageTemp.getTotalPage() ; i++){
			
			//新增insertList 
			List<BaseOrganization> insertList = new ArrayList<BaseOrganization>();
			//更新updateList
			List<BaseOrganization> updateList = new ArrayList<BaseOrganization>();
			
			//同步时间
			String sysTime = DateUtils.getStrDate(new Date(), DateUtils.STRDATE_1+DateUtils.HOURS_MINUTES_SECONDS);
			//初始化查询页数
			Page<DepartmentV> page = new Page<DepartmentV>(i, QUERY_NUM,TOTAL_COUNT);
			example.setPage(page);
			//获取查询结果
			List<DepartmentV> listDep = departmentVMapper.selectByExample(example);
			//查询结果封装在page中
			//page.setResultList(list);   //同步时不返回页面不做此方法
			
			//本地查询部门 通过（部门编号 org_code）
			List<String> listOrgCode = new ArrayList<String>();
			for(DepartmentV depv : listDep){
				listOrgCode.add((String) depv.getcDeptcode());
			}
			
			BaseOrganizationExample organizationExample = new BaseOrganizationExample();
			organizationExample.createCriteria().andOrgCodeIn(listOrgCode);
			List<BaseOrganization> listBaseOrg = baseOrganizationMapper.selectByExample(organizationExample);
			
			Map<String,Object>  mapBaseorg = new HashMap<String, Object>();
			
			for(BaseOrganization baseOrg : listBaseOrg){
				mapBaseorg.put(baseOrg.getOrgCode(), baseOrg);
			}
			//对查询结果进行更新或者插入操作
			for(DepartmentV dep : listDep){
				
				BaseOrganization baseOrg = (BaseOrganization) mapBaseorg.get((String)dep.getcDeptcode());
				if(baseOrg == null){
					baseOrg = new BaseOrganization();
				}
			
				baseOrg.setContactPerson((String)dep.getcLeader());//分管领导
				baseOrg.setName(dep.getcDeptname());//部门名称
				baseOrg.setOrgCode(dep.getcDeptcode());//部门编号
				baseOrg.setParentOrgCode(dep.getcParentdeptcode());//上级部门编号
				baseOrg.setStatus(StatusConstants.CREATED);
				if(dep.getcDeptcode().matches("\\d{4}")){
					baseOrg.setOrgType(0);
				}else if(dep.getcDeptcode().matches("\\d{8}")){
					baseOrg.setOrgType(1);
				}else if(dep.getcDeptcode().matches("\\d{12}")){
					baseOrg.setOrgType(2);
				}else if(dep.getcDeptcode().matches("\\d{16}")){
					baseOrg.setOrgType(3);
				}
				
				if(baseOrg.getOrgId() == null){
					insertList.add(baseOrg);
					baseOrg.setCreateTime(new Date());
					baseOrg.setUpdateTime(new Date());
				}else{
					updateList.add(baseOrg);
					baseOrg.setUpdateTime(new Date());
				}
			}
			
			if (updateList.size() > 0) {
				inserOrUpdate(updateList,false);
			}
			if (insertList.size() > 0) {
				inserOrUpdate(insertList,true);
			}
			logger.info("同步营业部门>>>>>>第{}次同步，--->同步条数{}，同步时间{}",i,listDep.size(),sysTime);
			
		}
		
	}
	
	
	/**
	 * 
	 * TODO 循环插入 或 更新
	 * @author 黄瑞庆
	 * void
	 * @param list 出入对象集合
	 * @param isInsert true:插入
	 * 2017年3月2日 下午4:02:19
	 */
	public void inserOrUpdate(List<BaseOrganization> list , Boolean isInsert){
		
		for(BaseOrganization baseOrg : list){
			if(isInsert){
				baseOrganizationMapper.insertSelective(baseOrg);
			}else{
				baseOrganizationMapper.updateByPrimaryKeySelective(baseOrg);
			}
		}
	}
	

}
